package com.fjwt.gz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.entity.SysUser;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.AwardCouponBo;
import com.fjwt.gz.coupon.SelfOperatedCouponsImpl;
import com.fjwt.gz.db.dto.AuAuditRecordsDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ActivityVO;
import com.fjwt.gz.db.vo.AuAuditRecordsVO;
import com.fjwt.gz.db.vo.CouponVO;
import com.fjwt.gz.service.mapper.ActivityMapper;
import com.fjwt.gz.service.mapper.AgentEmployeeMapper;
import com.fjwt.gz.service.mapper.AuAuditRecordsMapper;
import com.fjwt.gz.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动审批记录表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AuAuditRecordsService extends ServiceImpl<AuAuditRecordsMapper, AuAuditRecordsEntity> {

    @Resource
    private AuAuditRecordsMapper auditRecordsMapper;

    @Autowired
    protected SelfOperatedCouponsImpl selfOperatedCoupons;

    @Autowired
    private FansAuthService fansAuthService;

    @Resource
    private AuAuditFlowService auditFlowService;

    @Resource
    private ActivityService activityService;

    @Resource
    private AwardCouponService awardCouponService;

    @Resource
    private AgentInfoService agentInfoService;

    @Resource
    private FansAgentService fansAgentService;

    @Resource
    private ActivityMapper activityMapper;

    @Autowired
    private AgentAppService agentAppService;

    @Resource
    private AgentEmployeeMapper agentEmployeeMapper;

    @Autowired
    private PayAuthService payAuthService;
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private ActivityAppService activityAppService;
    @Autowired
    private MchChannelService mchChannelService;
    @Autowired
    private AuAuditService auAuditService;
    @Autowired
    private AwardGoodsService awardGoodsService;
    @Autowired
    private AwardScoreService awardScoreService;
    @Autowired
    private AwardVirtualService awardVirtualService;

    /**
     * 查询审批记录列表
     *
     * @param iPage 分页
     * @param auditRecordsDTO 查询参数
     * @return
     */
    public IPage<AuAuditRecordsVO> selectAuditRecordList(IPage iPage, AuAuditRecordsDTO auditRecordsDTO) {
        IPage<AuAuditRecordsVO> page = baseMapper.selectAuditRecordsEntityPage(iPage, auditRecordsDTO);
        List<AuAuditRecordsVO> records = page.getRecords();
        if (ObjectUtils.isNotEmpty(records)) {
            Map<Long, List<CouponVO>> activityAwardMap = new HashMap<>();
            Map<Long, String> activityAgentNoMap = new HashMap<>();
            Map<Long, AuAuditRecordsVO> managerActivityMap = new HashMap<>();
            // 筛选活动的卡券
            Set<Long> activityIds = records.stream().map(AuAuditRecordsVO::getActivityId).collect(Collectors.toSet());
            if (ObjectUtils.isNotEmpty(activityIds)) {
                // 查询活动卡券奖品信息
                List<CouponVO> activityAwardList = activityAwardService.getCouponByActivityIds(activityIds);
                if (ObjectUtils.isNotEmpty(activityAwardList)) {
                    activityAwardMap = activityAwardList.stream().collect(Collectors.groupingBy(CouponVO::getActivityId,
                            Collectors.mapping(item -> {
                                item.setThirdParam(item.getPayConfig());
                                item.setPayConfig(null);
                                item.setPayAuthId(null);
                                return item;
                            }, Collectors.toList())));
                }
                if (Constants.AUDIT_INFO_TYPE.PROXY.equals(auditRecordsDTO.getInfoType())) {
                    // 机构端查询活动挂载机构号
                    List<ActivityVO> activityAgentNos = activityAppService.getActivityAgentNo(Constants.AGENT_APP_TYPE.WX_LITE, activityIds);
                    if (ObjectUtils.isNotEmpty(activityAgentNos)) {
                        activityAgentNoMap = activityAgentNos.stream().collect(Collectors.toMap(ActivityVO::getActivityId, ActivityVO::getAgentNo));
                    }
                }else if (Constants.AUDIT_INFO_TYPE.MANAGE.equals(auditRecordsDTO.getInfoType())){
                    // 运营端筛选出运营创建的活动
                    List<AuAuditRecordsVO> managerActivityVOS = baseMapper.selectManagerActivity(activityIds);
                    if (ObjectUtils.isNotEmpty(managerActivityVOS)) {
                        managerActivityMap = managerActivityVOS.stream().collect(Collectors.toMap(AuAuditRecordsVO::getActivityId, Function.identity()));
                    }
                }
            }
            for (AuAuditRecordsVO record : records) {
                if (Constants.AUDIT_INFO_TYPE.PROXY.equals(record.getInfoType())) {
                    AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(record.getInfoId());
                    if (ObjectUtils.isNotEmpty(agentInfo)) {
                        record.setAgentName(agentInfo.getAgentName());
                        record.setPendingReviewAgent(agentInfo.getAgentName());
                    }
                    if (ObjectUtils.isNotEmpty(auditRecordsDTO.getAgentNo()) && auditRecordsDTO.getAgentNo().equals(activityAgentNoMap.get(record.getActivityId()))) {
                        // 挂载机构需上传回执函
                        record.setIsReceipt(true);
                        // 也可下载回执函
                        record.setIsDownLoadReceipt(true);
                    }
                }else if (Constants.AUDIT_INFO_TYPE.MANAGE.equals(auditRecordsDTO.getInfoType())){
                    record.setPendingReviewAgent("运营");
                    // 运营可下载回执函
                    record.setIsDownLoadReceipt(true);
                    if (managerActivityMap.containsKey(record.getActivityId())) {
                        // 运营自建活动需上传回执函
                        record.setIsReceipt(true);
                    }
                }
                record.setCouponList(activityAwardMap.get(record.getActivityId()));
            }
        }
        return page;
    }

    /**
     * 添加审批记录
     * @param activityId
     * @param sysUser
     * @param auditFlowEntity
     * @param auditType
     * @param agentInfo
     */
    public void add(Long activityId, com.fjwt.gz.db.entity.SysUser sysUser, AuAuditFlowEntity auditFlowEntity, String auditType, AgentInfoEntity agentInfo) {
        AuAuditRecordsEntity dto = new AuAuditRecordsEntity();
        dto.setActivityId(activityId);
        dto.setAuditFlowId(auditFlowEntity.getAuditFlowId());
        dto.setAuditSerialNo("AUDIT"+Utils.generateBathNo());
        dto.setInfoType(auditType);
        dto.setState(0);
        dto.setSysUserId(sysUser.getSysUserId());
        auditRecordsMapper.insert(dto);
    }

    /**
     * 审批
     *
     * @param recordsDTO 审批记录详情
     * @param sysUser 登录用户
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void audit(AuAuditRecordsDTO recordsDTO, SysUser sysUser) {
        if (null == recordsDTO.getAuditRecordsId() || null == recordsDTO.getActivityId()
                || null == recordsDTO.getState() || StrUtil.isBlank(recordsDTO.getRemark())) {
            throw new BizException("请求参数缺失");
        }
        int i;
        // 根据id查询当前审批记录详情
        AuAuditRecordsEntity result = auditRecordsMapper.selectById(recordsDTO.getAuditRecordsId());
        AuAuditRecordsEntity dto = new AuAuditRecordsEntity();
        BeanUtils.copyProperties(result, dto);
        dto.setAuditTime(new Date());
        if (Constants.SYS_ROLE_TYPE.MANAGER.equals(sysUser.getSysType())) {
            dto.setInfoId(String.valueOf(sysUser.getSysUserId()));
        }
        dto.setSysUserId(sysUser.getSysUserId());
        dto.setRealName(sysUser.getRealname());
        dto.setTelphone(sysUser.getTelphone());
        dto.setState(recordsDTO.getState());
        dto.setRemark(recordsDTO.getRemark());
        i = auditRecordsMapper.updateById(dto);
        if (Constants.AUDIT_STATE.AUDIT_PASS == recordsDTO.getState()) {
            log.info("审批记录详情：{}", JSONObject.toJSONString(result));
            if (Constants.AUDIT_INFO_TYPE.PROXY.equals(result.getInfoType())) {
                // 判断活动是否是挂载机构审批的 如果是也需要上传回执函
                List<ActivityVO> activityAgentNos = activityAppService.getActivityAgentNo(Constants.AGENT_APP_TYPE.WX_LITE, List.of(recordsDTO.getActivityId()));
                if (ObjectUtils.isEmpty(activityAgentNos)) {
                    throw new BizException("未查询到活动挂载小程序机构号，请驳回");
                }
                if (ObjectUtils.isNotEmpty(activityAgentNos) && sysUser.getBelongInfoId().equals(activityAgentNos.get(0).getAgentNo()) && ObjectUtils.isEmpty(recordsDTO.getOssFileUrl())) {
                    throw new BizException("请上传回执函");
                }
                // 获取活动的审批流程
                AuAuditEntity auditEntity = auAuditService.getBaseMapper().selectByAuditType(Constants.AUDIT_TYPE.ACTIVITY);
                if (null == auditEntity) {
                    throw new BizException("审批类型不存在");
                }
                // 查询当前机构
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(sysUser.getBelongInfoId());
                AuAuditRecordsEntity auAuditRecordsEntity = new AuAuditRecordsEntity();
                auAuditRecordsEntity.setActivityId(recordsDTO.getActivityId());
                auAuditRecordsEntity.setAuditSerialNo("AUDIT"+ Utils.generateBathNo());
                auAuditRecordsEntity.setState(Constants.AUDIT_STATE.UN_AUDIT);
                // 如果本次审批是活动挂载的小程序机构本级审 通过后直接让运营审
                if (sysUser.getBelongInfoId().equals(activityAgentNos.get(0).getAgentNo())) {
                    AuAuditFlowEntity auditFlowEntity = auditFlowService.getBaseMapper().selectAuditFlowByAuditIdAndLevel(auditEntity.getAuditId(), 0);
                    auAuditRecordsEntity.setAuditFlowId(auditFlowEntity.getAuditFlowId());
                    auAuditRecordsEntity.setInfoType(Constants.AUDIT_INFO_TYPE.MANAGE);
                }else {
                    // 不是本级直接让上级审
                    // 获取上级机构的审批流程
                    int auditLevel = agentInfo.getLevel() - 1;
                    AuAuditFlowEntity auditFlow = auditFlowService.getBaseMapper().selectAuditFlowByAuditIdAndLevel(auditEntity.getAuditId(), auditLevel);
                    auAuditRecordsEntity.setAuditFlowId(auditFlow.getAuditFlowId());
                    auAuditRecordsEntity.setInfoType(Constants.AUDIT_INFO_TYPE.PROXY);
                    switch (auditLevel) {
                        case 0 -> {
                            auAuditRecordsEntity.setInfoId(null);
                            auAuditRecordsEntity.setInfoType(Constants.AUDIT_INFO_TYPE.MANAGE);
                        }
                        case 1 -> auAuditRecordsEntity.setInfoId(agentInfo.getAgentNo1());
                        case 2 -> auAuditRecordsEntity.setInfoId(agentInfo.getAgentNo2());
                        case 3 -> auAuditRecordsEntity.setInfoId(agentInfo.getAgentNo3());
                        default -> throw new BizException("审批级别异常");
                    }
                }
                i = auditRecordsMapper.insert(auAuditRecordsEntity);
            }
            if (Constants.AUDIT_INFO_TYPE.MANAGE.equals(result.getInfoType())) {
                // 判断活动是否是运营直接创建的 运营创建的也需要上传回执函
                List<AuAuditRecordsVO> auAuditRecordsVOS = baseMapper.selectManagerActivity(List.of(recordsDTO.getActivityId()));
                if (ObjectUtils.isNotEmpty(auAuditRecordsVOS) && ObjectUtils.isEmpty(recordsDTO.getOssFileUrl())) {
                    throw new BizException("请上传回执函");
                }
                ActivityEntity activityEntity = activityService.getById(recordsDTO.getActivityId());
                ActivityEntity activity = new ActivityEntity();
                BeanUtils.copyProperties(activityEntity, activity);
                activity.setState(Constants.ACTIVITY_STATE.PASS);
                activityService.checkActivityCouponThirdParam(recordsDTO.getActivityId());
                i = activityService.updateById(activity) ? 1 : 0;
            }
        } else {
            i = updateActivityState(recordsDTO, Constants.ACTIVITY_STATE.REJECT);
        }
        if (i <=0){
            throw new BizException("审批失败");
        }
    }

    /**
     * 修改活动和奖品状态
     * @param recordsDTO
     * @return
     */
    private int updateActivityState(AuAuditRecordsDTO recordsDTO, Integer state) {
        int i;
        // 修改活动状态
        ActivityEntity activityEntity = activityService.getById(recordsDTO.getActivityId());
        ActivityEntity activity = new ActivityEntity();
        BeanUtils.copyProperties(activityEntity, activity);
        activity.setState(state);
        activity.setErrorInfo(recordsDTO.getRemark());
        i = activityService.updateById(activity) ? 1 : 0;
        // 修改活动奖品状态
        List<ActivityAwardEntity> activityAwardList = activityAwardService.list(ActivityAwardEntity.gw().eq(ActivityAwardEntity::getActivityId, activity.getActivityId()));
        if (ObjectUtils.isNotEmpty(activityAwardList)) {
            Map<Integer, List<Long>> activityAwardIdsMap = activityAwardList.stream().collect(Collectors.groupingBy(ActivityAwardEntity::getAwardType,
                    Collectors.mapping(ActivityAwardEntity::getAwardId, Collectors.toList())));
            activityAwardIdsMap.forEach((awardType, awardIds) -> {
                switch (awardType) {
                    case Constants.AWARD.COUPON -> awardCouponService.lambdaUpdate()
                            .in(AwardCouponEntity::getCouponId, awardIds)
                            .set(AwardCouponEntity::getState, Constants.AWARD_STATE.DRAFT).update();
                    case Constants.AWARD.GOODS -> awardGoodsService.lambdaUpdate()
                            .in(AwardGoodsEntity::getGoodsId, awardIds)
                            .set(AwardGoodsEntity::getState, Constants.AWARD_STATE.DRAFT).update();
                    case Constants.AWARD.SCORE -> awardScoreService.lambdaUpdate()
                            .in(AwardScoreEntity::getScoreId, awardIds)
                            .set(AwardScoreEntity::getState, Constants.AWARD_STATE.DRAFT).update();
                    case Constants.AWARD.VIRTUAL_COUPON -> awardVirtualService.lambdaUpdate()
                            .in(AwardVirtualEntity::getVirtualId, awardIds)
                            .set(AwardVirtualEntity::getState, Constants.AWARD_STATE.DRAFT).update();
                    default -> throw new BizException("活动配置奖品类型有误");
                }
            });
        }
        return i;
    }

    /**
     * 卡券参数信息回执，更改活动状态
     *
     * @param recordsDTO
     * @return
     */
    @Transactional
    public void couponReceiptInfo(AuAuditRecordsDTO recordsDTO) {
        log.info("卡券参数回执：{}", JSONObject.toJSONString(recordsDTO));
        if (ObjectUtils.isEmpty(recordsDTO.getCouponList()) || recordsDTO.getActivityId() == null) {
            throw new BizException("请求参数缺失");
        }
        //获取活动详情
        ActivityEntity activityEntity = activityService.getById(recordsDTO.getActivityId());
        List<AwardCouponEntity> awardCouponList = new ArrayList<>();
        for (CouponVO couponVO : recordsDTO.getCouponList()) {
            AwardCouponEntity awardCouponEntity = new AwardCouponEntity();
            awardCouponEntity.setCouponId(couponVO.getCouponId());
            awardCouponEntity.setPayConfig(couponVO.getPayConfig());
            awardCouponList.add(awardCouponEntity);
        }
        if (ObjectUtils.isNotEmpty(awardCouponList)) {
            awardCouponService.updateBatchById(awardCouponList);
        }
        ActivityEntity dto = new ActivityEntity();
        BeanUtils.copyProperties(activityEntity, dto);
        dto.setState(Constants.ACTIVITY_STATE.RECEIPT);
        boolean flag = activityService.updateById(dto);
        if (!flag){
            throw new BizException("操作失败");
        }
    }

    /**
     * 商家审批
     * @param entity
     * @param sysUser
     * @return
     */
    @Transactional
    public int mchaudit(AuAuditRecordsEntity entity,com.fjwt.gz.core.entity.SysUser sysUser,Long fansId) {

        LambdaQueryWrapper<FansAgentEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FansAgentEntity::getFansId, fansId);
        FansAgentEntity  fansAuthEntity = fansAgentService.getOne(queryWrapper);
        AgentEmployeeEntity agentEmployee = agentEmployeeMapper.selectById(fansAuthEntity.getAgentEmployeeId());
        int i = 0;
        AuAuditRecordsEntity result = auditRecordsMapper.selectById(entity.getAuditRecordsId());
        AuAuditRecordsEntity dto = new AuAuditRecordsEntity();
        BeanUtils.copyProperties(result,dto);
        dto.setAuditTime(new Date());
        dto.setInfoId(String.valueOf(sysUser.getSysUserId()));
        dto.setSysUserId(sysUser.getSysUserId());
        dto.setRealName(sysUser.getRealname());
        dto.setTelphone(sysUser.getTelphone());
        dto.setState(entity.getState());
        dto.setRemark(entity.getRemark());
        i = auditRecordsMapper.updateById(dto);

        if(1 == entity.getState()){
            // 判断是否为最后一级审批
            AgentInfoEntity agentInfo = agentInfoService.getBaseMapper().selectById(agentEmployee.getAgentNo());
            log.info("审批记录详情：{}", JSONObject.toJSONString(result));
            if (agentInfo.getLevel() == 2){
                ActivityEntity activityEntity = activityService.getById(entity.getActivityId());
                ActivityEntity activity = new ActivityEntity();
                BeanUtils.copyProperties(activityEntity,activity);
                activity.setState(4);

                i = activityService.updateById(activity)?1:0;
                if (i == 1){
                    return 100086;
                }
            }else if (agentInfo.getLevel() == 3){
//                AuditFlowEntity auditFlow = auditFlowService.getBaseMapper().selectAuditFlowByInfoType(Constants.AUDIT_INFO_TYPE.FANS);
                AuAuditRecordsEntity record = new AuAuditRecordsEntity();
                record.setActivityId(entity.getActivityId());
                record.setAuditFlowId(4L);
                record.setAuditSerialNo("AUDIT"+Utils.generateBathNo());
                record.setInfoType("fans");
                record.setState(0);
                i = auditRecordsMapper.insert(record);
            }else {
                throw new ServiceException("级别不足,审批失败");
            }
        }else{
            ActivityEntity activityEntity = activityService.getById(entity.getActivityId());
            ActivityEntity activity = new ActivityEntity();
            BeanUtils.copyProperties(activityEntity,activity);
            activity.setState(3);
            activity.setErrorInfo(entity.getRemark());
            i = activityService.updateById(activity)?1:0;
        }
        return i;
    }

    /**
     * 商户自主发券审批
     * @param entity
     * @param sysUser
     * @return
     */
    @Transactional
    public int mchAudit(AuAuditRecordsEntity entity,com.fjwt.gz.core.entity.SysUser sysUser) {
        LambdaQueryWrapper<AuAuditRecordsEntity> wrapper = AuAuditRecordsEntity.gw();
        wrapper.eq(AuAuditRecordsEntity::getActivityId,entity.getActivityId())
                .eq(AuAuditRecordsEntity::getState,0);
        AuAuditRecordsEntity one = auditRecordsMapper.selectOne(wrapper);
        if (one != null){
            if (entity.getState() == 1){
                if (one.getAuditFlowId() == 4L){
                    one.setAuditTime(new Date());
                    one.setInfoId(String.valueOf(sysUser.getSysUserId()));
                    one.setSysUserId(sysUser.getSysUserId());
                    one.setRealName(sysUser.getRealname());
                    one.setTelphone(sysUser.getTelphone());
                    one.setState(1);
                    one.setRemark("运营端自主审核通过");
                    auditRecordsMapper.updateById(one);
                    upMchCoupion(entity.getActivityId(),1,entity);

                }else if (one.getAuditFlowId() == 5L){
                    one.setAuditTime(new Date());
                    one.setInfoId(String.valueOf(sysUser.getSysUserId()));
                    one.setSysUserId(sysUser.getSysUserId());
                    one.setRealName(sysUser.getRealname());
                    one.setTelphone(sysUser.getTelphone());
                    one.setState(1);
                    one.setRemark("运营端自主审核通过");
                    auditRecordsMapper.updateById(one);
                    one.setAuditRecordsId(null);
                    one.setAuditSerialNo("AUDIT"+Utils.generateBathNo());
                    one.setAuditFlowId(4L);
                    auditRecordsMapper.insert(one);
                    upMchCoupion(entity.getActivityId(),1,entity);
                }
            }else if (entity.getState() == 2){
                if (one.getAuditFlowId() == 4L){
                    one.setAuditTime(new Date());
                    one.setInfoId(String.valueOf(sysUser.getSysUserId()));
                    one.setSysUserId(sysUser.getSysUserId());
                    one.setRealName(sysUser.getRealname());
                    one.setTelphone(sysUser.getTelphone());
                    one.setState(2);
                    one.setRemark(entity.getRemark());
                    auditRecordsMapper.updateById(one);
                    upMchCoupion(entity.getActivityId(),0,entity);
                }else if (one.getAuditFlowId() == 5L){
                    one.setAuditTime(new Date());
                    one.setInfoId(String.valueOf(sysUser.getSysUserId()));
                    one.setSysUserId(sysUser.getSysUserId());
                    one.setRealName(sysUser.getRealname());
                    one.setTelphone(sysUser.getTelphone());
                    one.setState(2);
                    one.setRemark(entity.getRemark());
                    auditRecordsMapper.updateById(one);
                    upMchCoupion(entity.getActivityId(),0,entity);
                }
            }

        }else {
            throw new ServiceException("数据异常，请联刷新重试");
        }

        return 1;
    }

    public void upMchCoupion(Long activityId,Integer state,AuAuditRecordsEntity entity) {
        if (state == 1){
            ActivityEntity activityEntity = activityService.getById(activityId);
            activityEntity.setState(4);
            activityService.updateById(activityEntity);
            Map map = activityMapper.selectActivitys(String.valueOf(activityId));
            String awardId = map.get("awardId").toString();
            AwardCouponEntity couponAwardEntity = awardCouponService.getById(awardId);
            couponAwardEntity.setState(2);
            awardCouponService.updateById(couponAwardEntity);
        }
        if (state == 0){
            ActivityEntity activityEntity = activityService.getById(activityId);
            activityEntity.setState(3);
            activityEntity.setErrorInfo(entity.getRemark());
            activityService.updateById(activityEntity);
            Map map = activityMapper.selectActivitys(String.valueOf(activityId));
            String awardId = map.get("awardId").toString();
            AwardCouponEntity couponAwardEntity = awardCouponService.getById(awardId);
            couponAwardEntity.setState(1);
            awardCouponService.updateById(couponAwardEntity);
        }

    }

    public Integer audits(AuAuditRecordsEntity entity,Long awardId,Long fansId,Long userId,String appId) throws Exception {

        SysUser sysUser = new SysUser();
        AgentAppEntity agentAppEntity = agentAppService.lambdaQuery().eq(AgentAppEntity::getAppId,appId).eq(AgentAppEntity::getType,1).one();
        LambdaQueryWrapper<FansAuthEntity> wrapper = FansAuthEntity.gw();
        wrapper.eq(FansAuthEntity::getFansId,fansId);
        wrapper.eq(FansAuthEntity::getAgentNo,agentAppEntity.getAgentNo());
        FansAuthEntity fansAuthEntity = fansAuthService.getBaseMapper().selectOne(wrapper);
        log.info("系统用户信息：{}", JSONObject.toJSONString(sysUser));
        sysUser.setSysUserId(userId);
        if (fansAuthEntity == null){
            sysUser.setRealname("暂无真实姓名");
            sysUser.setTelphone("暂无真实手机号");
        }else {
            sysUser.setRealname(fansAuthEntity.getCstmName());
            sysUser.setTelphone(fansAuthEntity.getAuthPhone());
        }

        int audit = this.mchaudit(entity, sysUser, fansId);
        if (audit == 100086) {
            ActivityEntity activityEn = activityService.getBaseMapper().selectById(entity.getActivityId());
            String activityJson = activityEn.getRemark();

            AwardCouponEntity couponAwardEntity = JSONObject.parseObject(activityJson, AwardCouponEntity.class);
            JSONObject payConfigJson = JSONObject.parseObject(couponAwardEntity.getPayConfig());
            AwardCouponBo awardCouponBo = new AwardCouponBo();
            com.fjwt.gz.util.quartz.BeanUtils.copyProperties(couponAwardEntity, awardCouponBo);
            MchChannelEntity mchChannelEntity = mchChannelService.getOne(MchChannelEntity.gw().eq(MchChannelEntity::getMchNo, couponAwardEntity.getMchNo()).eq(MchChannelEntity::getIfCode, "gtpay"));
            awardCouponBo.setWechatSubmerchantNo(mchChannelEntity.getWechatSubmerchantNo());

            JSONObject jsonObject = selfOperatedCoupons.response(awardCouponBo, payConfigJson.getString("outRequestNo"));

            AwardCouponEntity awardCouponEntity = awardCouponService.getBaseMapper().selectById(awardId);
//            jsonObject.put("appid", "wx313cfd5a1d78e709");
//            jsonObject.put("outRequestNo", payConfigJson.getString("outRequestNo"));
            awardCouponEntity.setPayConfig(jsonObject.getString("stock_id"));
            awardCouponService.updateById(awardCouponEntity);
        }
        return audit;
    }

    /**
     * 撤销审批
     * @param auditRecordsDTO
     * @param sysUser
     */
    @Transactional
    public void revoke(AuAuditRecordsDTO auditRecordsDTO, SysUser sysUser) {
        if (ObjectUtils.isEmpty(auditRecordsDTO.getActivityId())) {
            throw new BizException("请选择要撤销的活动");
        }
        ActivityEntity activityEntity = activityService.getById(auditRecordsDTO.getActivityId());
        if (ObjectUtils.isEmpty(activityEntity) || ObjectUtils.isEmpty(activityEntity.getState())) {
            throw new BizException("活动信息异常");
        }
        if (Constants.ACTIVITY_STATE.EXAMINE != activityEntity.getState()) {
            throw new BizException("活动未在审批中，请检查");
        }
        LambdaQueryWrapper<AuAuditRecordsEntity> gw = AuAuditRecordsEntity.gw()
                .eq(AuAuditRecordsEntity::getActivityId, auditRecordsDTO.getActivityId())
                .eq(AuAuditRecordsEntity::getState, Constants.AUDIT_STATE.UN_AUDIT);
        AuAuditRecordsEntity auditRecordsEntity = this.baseMapper.selectOne(gw);
        if (ObjectUtils.isEmpty(auditRecordsEntity)) {
            throw new BizException("未查询到活动待审批记录");
        }
        auditRecordsEntity.setState(Constants.AUDIT_STATE.AUDIT_REVOKE);
        auditRecordsEntity.setSysUserId(sysUser.getSysUserId());
        auditRecordsEntity.setRealName(sysUser.getRealname());
        auditRecordsEntity.setTelphone(sysUser.getTelphone());
        baseMapper.updateById(auditRecordsEntity);

        // 修改活动状态
        updateActivityState(auditRecordsDTO, Constants.ACTIVITY_STATE.DRAFT);
    }
}
